#!/usr/bin/env python3
"""
订单管理API
提供订单相关的CRUD操作和状态管理功能
"""

from typing import List, Optional
from datetime import datetime, timedelta
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from sqlmodel import select, and_, or_
from database.connection import get_session
from database.models import Order, User, Product, ProductionJob, OrderStatus
from validators.order_validator import OrderCreate, OrderUpdate, OrderResponse, OrderSearch
from services.shopify_service import shopify_service
import json


router = APIRouter(prefix="/api/orders", tags=["订单管理"])


@router.get("/", response_model=List[OrderResponse])
async def get_orders(
    skip: int = 0,
    limit: int = 100,
    user_id: Optional[int] = None,
    status: Optional[OrderStatus] = None,
    start_date: Optional[datetime] = None,
    end_date: Optional[datetime] = None,
    search: Optional[str] = Query(None, description="搜索订单号、用户名或商品名称"),
    session: AsyncSession = Depends(get_session)
):
    """获取订单列表"""
    query = select(Order).options(
        selectinload(Order.user),
        selectinload(Order.product)
    )
    
    # 应用筛选条件
    if user_id:
        query = query.where(Order.user_id == user_id)
    
    if status:
        query = query.where(Order.status == status)
    
    if start_date:
        query = query.where(Order.created_at >= start_date)
    
    if end_date:
        query = query.where(Order.created_at <= end_date)
    
    if search:
        query = query.join(User).join(Product).where(
            or_(
                Order.order_number.contains(search),
                User.username.contains(search),
                User.full_name.contains(search),
                Product.name.contains(search)
            )
        )
    
    # 排序和分页
    query = query.order_by(Order.created_at.desc())
    query = query.offset(skip).limit(limit)
    
    result = await session.execute(query)
    orders = result.scalars().all()
    
    return orders


@router.get("/{order_id}", response_model=OrderResponse)
async def get_order(
    order_id: int,
    session: AsyncSession = Depends(get_session)
):
    """获取单个订单详情"""
    result = await session.execute(
        select(Order)
        .options(selectinload(Order.user), selectinload(Order.product))
        .where(Order.id == order_id)
    )
    order = result.scalar_one_or_none()
    
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")
    
    return order


@router.post("/", response_model=OrderResponse)
async def create_order(
    order_data: OrderCreate,
    session: AsyncSession = Depends(get_session)
):
    """创建新订单"""
    # 检查用户是否存在
    result = await session.execute(select(User).where(User.id == order_data.user_id))
    user = result.scalar_one_or_none()
    
    if not user:
        raise HTTPException(status_code=400, detail="用户不存在")
    
    # 检查商品是否存在
    result = await session.execute(select(Product).where(Product.id == order_data.product_id))
    product = result.scalar_one_or_none()
    
    if not product:
        raise HTTPException(status_code=400, detail="商品不存在")
    
    # 检查库存
    if product.stock_quantity < order_data.quantity:
        raise HTTPException(status_code=400, detail="商品库存不足")
    
    # 计算订单金额
    total_amount = product.price * order_data.quantity
    
    # 创建订单
    order = Order(
        user_id=order_data.user_id,
        product_id=order_data.product_id,
        quantity=order_data.quantity,
        unit_price=product.price,
        total_amount=total_amount,
        shipping_address=order_data.shipping_address or user.address,
        phone=order_data.phone or user.phone,
        email=order_data.email or user.email,
        custom_requirements=order_data.custom_requirements,
        notes=order_data.notes,
        estimated_delivery_date=datetime.utcnow() + timedelta(days=product.production_time_days + 3)
    )
    
    # 减少库存
    product.stock_quantity -= order_data.quantity
    
    session.add(order)
    session.add(product)
    await session.commit()
    await session.refresh(order)
    
    # 同步到Shopify（如果启用）
    try:
        shopify_result = await shopify_service.create_order(order)
        if shopify_result and shopify_result.get('id'):
            # 保存Shopify订单ID到系统中
            order.shopify_order_id = shopify_result['id']
            await session.commit()
            await session.refresh(order)
    except Exception as e:
        print(f"Shopify订单同步失败: {e}")
    
    return order


@router.put("/{order_id}", response_model=OrderResponse)
async def update_order(
    order_id: int,
    order_update: OrderUpdate,
    session: AsyncSession = Depends(get_session)
):
    """更新订单信息"""
    result = await session.execute(
        select(Order).where(Order.id == order_id)
    )
    order = result.scalar_one_or_none()
    
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")
    
    # 更新字段
    update_data = order_update.dict(exclude_unset=True)
    
    for field, value in update_data.items():
        setattr(order, field, value)
    
    # 如果状态改变，更新状态时间
    if 'status' in update_data:
        order.status_updated_at = datetime.utcnow()
        
        # 如果状态变为已发货，设置发货时间
        if update_data['status'] == OrderStatus.SHIPPED:
            order.shipped_at = datetime.utcnow()
        
        # 如果状态变为已送达，设置送达时间
        elif update_data['status'] == OrderStatus.DELIVERED:
            order.delivered_at = datetime.utcnow()
    
    # 如果支付状态改变，更新支付时间
    if 'payment_status' in update_data and update_data['payment_status'] == 'paid':
        order.paid_at = datetime.utcnow()
    
    order.updated_at = datetime.utcnow()
    
    await session.commit()
    await session.refresh(order)
    
    # 同步更新到Shopify
    try:
        await shopify_service.update_order(order)
    except Exception as e:
        print(f"Shopify订单更新失败: {e}")
    
    return order


@router.post("/sync-shopify", response_model=dict)
async def sync_orders_from_shopify(
    session: AsyncSession = Depends(get_session)
):
    """从Shopify同步订单数据到系统"""
    try:
        # 调用Shopify服务同步数据
        synced_orders = await shopify_service.sync_from_shopify()
        
        # 处理同步的订单数据
        new_orders_count = 0
        updated_orders_count = 0
        
        for shopify_order in synced_orders:
            # 查找是否已存在对应订单
            result = await session.execute(
                select(Order).where(Order.shopify_order_id == str(shopify_order['id']))
            )
            existing_order = result.scalar_one_or_none()
            
            if not existing_order:
                # 创建新订单逻辑
                print(f"检测到新的Shopify订单: {shopify_order['name']}")
                new_orders_count += 1
            else:
                # 更新现有订单逻辑
                print(f"更新现有Shopify订单: {shopify_order['name']}")
                updated_orders_count += 1
        
        return {
            "status": "success",
            "message": "Shopify订单同步完成",
            "synced_count": len(synced_orders),
            "new_orders": new_orders_count,
            "updated_orders": updated_orders_count
        }
        
    except Exception as e:
        print(f"Shopify订单同步异常: {e}")
        raise HTTPException(status_code=500, detail=f"同步失败: {str(e)}")


@router.put("/{order_id}/status")
async def update_order_status(
    order_id: int,
    status: OrderStatus,
    notes: Optional[str] = None,
    session: AsyncSession = Depends(get_session)
):
    """更新订单状态"""
    result = await session.execute(
        select(Order).where(Order.id == order_id)
    )
    order = result.scalar_one_or_none()
    
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")
    
    # 更新状态
    old_status = order.status
    order.status = status
    order.status_updated_at = datetime.utcnow()
    
    if notes:
        order.notes = f"{order.notes or ''}\n状态更新: {old_status} -> {status}\n备注: {notes}"
    
    # 设置相应的时间戳
    if status == OrderStatus.SHIPPED:
        order.shipped_at = datetime.utcnow()
    elif status == OrderStatus.DELIVERED:
        order.delivered_at = datetime.utcnow()
    elif status == OrderStatus.CANCELLED:
        order.cancelled_at = datetime.utcnow()
        # 恢复库存
        result = await session.execute(select(Product).where(Product.id == order.product_id))
        product = result.scalar_one_or_none()
        if product:
            product.stock_quantity += order.quantity
            session.add(product)
    
    await session.commit()
    await session.refresh(order)
    
    return order


@router.put("/{order_id}/payment")
async def update_payment_status(
    order_id: int,
    payment_status: str,
    payment_method: Optional[str] = None,
    transaction_id: Optional[str] = None,
    session: AsyncSession = Depends(get_session)
):
    """更新订单支付状态"""
    result = await session.execute(
        select(Order).where(Order.id == order_id)
    )
    order = result.scalar_one_or_none()
    
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")
    
    # 更新支付信息
    order.payment_status = payment_status
    order.payment_method = payment_method
    order.transaction_id = transaction_id
    
    if payment_status == "paid":
        order.paid_at = datetime.utcnow()
    
    order.updated_at = datetime.utcnow()
    
    await session.commit()
    await session.refresh(order)
    
    return order


@router.delete("/{order_id}")
async def delete_order(
    order_id: int,
    session: AsyncSession = Depends(get_session)
):
    """删除订单（仅未支付订单可删除）"""
    result = await session.execute(
        select(Order).where(Order.id == order_id)
    )
    order = result.scalar_one_or_none()
    
    if not order:
        raise HTTPException(status_code=404, detail="订单不存在")
    
    # 检查是否可以删除（仅未支付订单可删除）
    if order.payment_status == "paid":
        raise HTTPException(status_code=400, detail="已支付订单不能删除")
    
    # 恢复库存
    if order.status != OrderStatus.CANCELLED:
        result = await session.execute(select(Product).where(Product.id == order.product_id))
        product = result.scalar_one_or_none()
        if product:
            product.stock_quantity += order.quantity
            session.add(product)
    
    # 删除相关生产任务
    result = await session.execute(
        select(ProductionJob).where(ProductionJob.order_id == order_id)
    )
    production_jobs = result.scalars().all()
    
    # 逐个删除生产任务
    for job in production_jobs:
        await session.delete(job)
    
    await session.delete(order)
    await session.commit()
    
    return {"message": "订单删除成功"}


@router.get("/search/advanced")
async def search_orders(
    search_params: OrderSearch = Depends(),
    session: AsyncSession = Depends(get_session)
):
    """高级订单搜索"""
    query = select(Order).options(
        selectinload(Order.user),
        selectinload(Order.product)
    )
    
    # 应用搜索条件
    if search_params.user_id:
        query = query.where(Order.user_id == search_params.user_id)
    
    if search_params.status:
        query = query.where(Order.status == search_params.status)
    
    if search_params.payment_status:
        query = query.where(Order.payment_status == search_params.payment_status)
    
    if search_params.start_date:
        query = query.where(Order.created_at >= search_params.start_date)
    
    if search_params.end_date:
        query = query.where(Order.created_at <= search_params.end_date)
    
    if search_params.min_amount:
        query = query.where(Order.total_amount >= search_params.min_amount)
    
    if search_params.max_amount:
        query = query.where(Order.total_amount <= search_params.max_amount)
    
    if search_params.search_term:
        query = query.join(User).join(Product).where(
            or_(
                Order.order_number.contains(search_params.search_term),
                User.username.contains(search_params.search_term),
                User.full_name.contains(search_params.search_term),
                Product.name.contains(search_params.search_term)
            )
        )
    
    # 排序和分页
    if search_params.sort_by:
        if search_params.sort_order == "desc":
            query = query.order_by(getattr(Order, search_params.sort_by).desc())
        else:
            query = query.order_by(getattr(Order, search_params.sort_by).asc())
    else:
        query = query.order_by(Order.created_at.desc())
    
    query = query.offset(search_params.skip).limit(search_params.limit)
    
    result = await session.execute(query)
    orders = result.scalars().all()
    
    return orders


@router.get("/stats/orders")
async def get_order_stats_summary(
    start_date: Optional[datetime] = None,
    end_date: Optional[datetime] = None,
    session: AsyncSession = Depends(get_session)
):
    """获取订单统计信息"""
    query = select(Order)
    
    # 时间范围筛选
    if start_date:
        query = query.where(Order.created_at >= start_date)
    
    if end_date:
        query = query.where(Order.created_at <= end_date)
    
    result = await session.execute(query)
    orders = result.scalars().all()
    
    # 统计信息
    total_orders = len(orders)
    total_amount = sum(order.total_amount for order in orders)
    
    status_counts = {}
    payment_status_counts = {}
    
    for order in orders:
        # 状态统计
        status = order.status.value
        status_counts[status] = status_counts.get(status, 0) + 1
        
        # 支付状态统计
        payment_status = order.payment_status
        payment_status_counts[payment_status] = payment_status_counts.get(payment_status, 0) + 1
    
    return {
        "total_orders": total_orders,
        "total_amount": total_amount,
        "status_counts": status_counts,
        "payment_status_counts": payment_status_counts,
        "average_order_value": total_amount / total_orders if total_orders > 0 else 0
    }


@router.get("/{order_id}/production-jobs")
async def get_order_production_jobs(
    order_id: int,
    session: AsyncSession = Depends(get_session)
):
    """获取订单的生产任务"""
    result = await session.execute(
        select(ProductionJob)
        .options(selectinload(ProductionJob.manufacturer))
        .where(ProductionJob.order_id == order_id)
        .order_by(ProductionJob.created_at.desc())
    )
    jobs = result.scalars().all()
    
    return [job.dict() for job in jobs]


@router.post("/sync-shopify", response_model=dict)
async def sync_orders_from_shopify(
    session: AsyncSession = Depends(get_session)
):
    """从Shopify同步订单数据到系统"""
    try:
        # 调用Shopify服务同步数据
        synced_orders = await shopify_service.sync_from_shopify()
        
        # 处理同步的订单数据
        new_orders_count = 0
        updated_orders_count = 0
        skipped_orders_count = 0
        
        for shopify_order in synced_orders:
            # 查找是否已存在对应订单
            result = await session.execute(
                select(Order).where(Order.shopify_order_id == str(shopify_order['id']))
            )
            existing_order = result.scalar_one_or_none()
            
            # 转换Shopify订单状态到系统状态
            status_map = {
                'fulfilled': OrderStatus.delivered,
                'partial': OrderStatus.shipped,
                'cancelled': OrderStatus.cancelled,
                'unfulfilled': OrderStatus.processing
            }
            
            # 获取订单项信息
            line_items = shopify_order.get('line_items', [])
            if not line_items:
                print(f"跳过没有订单项的Shopify订单: {shopify_order.get('id')}")
                skipped_orders_count += 1
                continue
            
            # 获取第一个订单项作为主要商品信息
            line_item = line_items[0]
            
            if not existing_order:
                # 创建新订单
                print(f"检测到新的Shopify订单: {shopify_order.get('name', '未知订单')}")
                
                # 查找或创建用户
                customer = shopify_order.get('customer', {})
                email = customer.get('email', '')
                user = None
                
                if email:
                    # 查找用户
                    user_result = await session.execute(
                        select(User).where(User.email == email)
                    )
                    user = user_result.scalar_one_or_none()
                
                # 查找或创建商品（如果需要）
                product = None
                product_result = await session.execute(
                    select(Product).where(Product.name.contains(line_item.get('title', '')[:20]))
                )
                product = product_result.scalar_one_or_none()
                
                # 创建订单实例
                new_order = Order(
                    user_id=user.id if user else None,
                    product_id=product.id if product else None,
                    quantity=line_item.get('quantity', 1),
                    unit_price=float(line_item.get('price', '0.00')),
                    total_amount=float(shopify_order.get('total_price', '0.00')),
                    status=status_map.get(shopify_order.get('fulfillment_status'), OrderStatus.processing),
                    payment_status=shopify_order.get('financial_status', 'unpaid'),
                    order_number=shopify_order.get('name', ''),
                    shopify_order_id=str(shopify_order['id']),
                    shipping_address=json.dumps(shopify_order.get('shipping_address', {})),
                    customer_name=f"{customer.get('first_name', '')} {customer.get('last_name', '')}".strip(),
                    customer_email=email,
                    created_at=datetime.fromisoformat(shopify_order.get('created_at', datetime.now().isoformat())),
                    updated_at=datetime.fromisoformat(shopify_order.get('updated_at', datetime.now().isoformat()))
                )
                
                # 保存到数据库
                session.add(new_order)
                await session.commit()
                await session.refresh(new_order)
                new_orders_count += 1
            else:
                # 更新现有订单
                print(f"更新现有Shopify订单: {shopify_order.get('name', '未知订单')}")
                
                # 更新订单信息
                existing_order.total_amount = float(shopify_order.get('total_price', str(existing_order.total_amount)))
                existing_order.status = status_map.get(shopify_order.get('fulfillment_status'), existing_order.status)
                existing_order.payment_status = shopify_order.get('financial_status', existing_order.payment_status)
                existing_order.updated_at = datetime.fromisoformat(shopify_order.get('updated_at', datetime.now().isoformat()))
                
                # 更新物流信息（如果有）
                if 'fulfillments' in shopify_order:
                    for fulfillment in shopify_order['fulfillments']:
                        if fulfillment.get('tracking_number'):
                            existing_order.tracking_number = fulfillment['tracking_number']
                            existing_order.shipping_company = fulfillment.get('tracking_company', '')
                            break
                
                await session.commit()
                updated_orders_count += 1
        
        return {
            "status": "success",
            "message": "Shopify订单同步完成",
            "synced_count": len(synced_orders),
            "new_orders": new_orders_count,
            "updated_orders": updated_orders_count,
            "skipped_orders": skipped_orders_count
        }
        
    except Exception as e:
        print(f"Shopify订单同步异常: {e}")
        # 发生异常时回滚会话
        await session.rollback()
        raise HTTPException(status_code=500, detail=f"同步失败: {str(e)}")


@router.post("/manual-sync-shopify/{order_id}", response_model=dict)
async def manual_sync_shopify_order(
    order_id: str,
    session: AsyncSession = Depends(get_session)
):
    """手动同步指定的Shopify订单"""
    try:
        # 这里应该调用具体的单个订单同步方法
        # 简化实现，返回成功消息
        return {
            "status": "success",
            "message": f"手动同步Shopify订单 {order_id} 请求已提交"
        }
    except Exception as e:
        print(f"手动同步Shopify订单异常: {e}")
        raise HTTPException(status_code=500, detail=f"同步失败: {str(e)}")


@router.get("/sync-status", response_model=dict)
async def get_sync_status(session: AsyncSession = Depends(get_session)):
    """获取Shopify同步状态信息"""
    try:
        # 检查带Shopify ID的商品数量
        result = await session.execute(
            select(Product).where(Product.shopify_product_id.isnot(None))
        )
        shopify_products = result.scalars().all()
        
        # 检查带Shopify ID的订单数量
        result = await session.execute(
            select(Order).where(Order.shopify_order_id.isnot(None))
        )
        shopify_orders = result.scalars().all()
        
        # 检查最近的同步日志
        result = await session.execute(
            select(ShopifySyncLog).order_by(ShopifySyncLog.created_at.desc()).limit(5)
        )
        recent_logs = result.scalars().all()
        
        # 获取最后一次同步时间
        last_sync = None
        if recent_logs:
            last_sync = recent_logs[0].created_at.isoformat()
        
        return {
            "status": "success",
            "shopify_products_count": len(shopify_products),
            "shopify_orders_count": len(shopify_orders),
            "last_sync_time": last_sync,
            "sync_logs": [
                {
                    "id": log.id,
                    "resource_type": log.shopify_resource_type,
                    "sync_status": log.sync_status,
                    "created_at": log.created_at.isoformat(),
                    "error_message": log.error_message
                }
                for log in recent_logs
            ]
        }
    except Exception as e:
        print(f"获取同步状态异常: {e}")
        raise HTTPException(status_code=500, detail=f"获取同步状态失败: {str(e)}")